"use client"

import {useEffect, useRef, useState} from "react";
import {fetchData} from "../apis/api.ts";
import {Button, Card, Flex, Input, InputRef, Space, Spin, Tooltip} from 'antd';
import "../styles/app.css";
import "../styles/font.css";
import { StarOutlined, CaretRightOutlined, SearchOutlined  } from '@ant-design/icons';
import IconComponent from "./IconComponent.tsx";
import Meta from "antd/es/card/Meta";
import IconComponentTitle from "./IconComponentTitle.tsx";
import {useNavigate} from "react-router-dom";

type AppDataType = {
    "page": number
    "pages": number
    "size": number
    "total": number
    "records": {
        "id": number
        "name": string
        "icon": string
        "description": string
        "categoryId": number
        "category":{
            "id": number
            "name": string
            "icon": string
        }
    }[]
}
type TemplateDataType = {
    "cats": {
        "id": number
        "name": string
        "icon": string
    }[]
}
export default function APPPage() {
    const navigate = useNavigate();

    const [appData, setApps] = useState<AppDataType | null>(null);
    const [templateData, setTemplate] = useState<TemplateDataType | null>(null);
    const [loadingA, setLoadingA] = useState<boolean>(true);
    const [loadingB, setLoadingB] = useState<boolean>(true);

    const inputRef = useRef<InputRef>(null);

    const [error, setError] = useState<string | null>(null);

    // 记录当前选中按钮的ID和搜索词
    const [selectedButtonId, setSelectedButtonId] = useState<number>(0);
    const [currentSearchStr, setSearchStr] = useState<string>("");

    const [searchButtonDisabled, setSearchButtonDisabled] = useState(true); // 初始化搜索按钮为禁用状态

    useEffect(() => {
        const getTemplate = async () => {
            try {
                const templateRequest = await fetchData('/app/template');
                setTemplate(templateRequest);
            } catch (error) {
                setError("Failed to fetch posts.");
            } finally {
                setLoadingA(false);
            }
        };

        getTemplate();
    }, []);

    useEffect(() => {
        const getApps = async () => {
            try {
                const appDataRequest = await fetchData('/app?size=40');
                setApps(appDataRequest);
            } catch (error) {
                setError("Failed to fetch posts.");
            } finally {
                setLoadingB(false);
            }
        };

        getApps();
    }, []);




    if (loadingA || loadingB) {
        return <div className="loading">
            <Spin tip="加载中..." size="large">
            </Spin>
        </div>;
    }

    if (error) {
        return <div>{error}</div>;
    }

    if (!appData) {
        return <div>No Data</div>;
    }
    if (!templateData) {
        return <div>No Data</div>;
    }


    // 更新助手中心分类 和 选中状态的函数
    const handleButtonClick = async (buttonId: number) => {
        // 重新读取助手中心分类
        try {
            const appDataRequest = await fetchData('/app?size=40&cid='+buttonId+"&search="+currentSearchStr);
            setApps(appDataRequest);
        } catch (error) {
            setError("Failed to fetch posts.");
        }

        // 更新选中状态
        setSelectedButtonId(buttonId);
    };

    // 助手中心-搜索按钮点击时
    const handleSearchClickV2 = async () => {
        // 重新读取助手中心分类
        const searchStr = inputRef.current?.input?.value ?? '';

        if (searchStr){
            try {
                const appDataRequest = await fetchData('/app?size=40&cid='+selectedButtonId+'&search='+searchStr);
                setApps(appDataRequest);
            } catch (error) {
                setError("Failed to fetch posts.");
            }

            setSearchStr(searchStr);
        }

    };

    // 助手中心-搜索内容改变时
    const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        // 搜索内容为空的时候，设置搜索按钮为禁用，反之则启用
        const searchStr = event.target.value;
        setSearchButtonDisabled(searchStr === "");
    };

    // 使用应用
    const handleUseApp = (appId: number) => {
        navigate('/dialog/'+appId);
    };
    // 收藏应用
    const handleSubscribeApp = (appId: number) => {
        console.log("收藏/取消收藏" + appId);
        // 这里可以包含其他业务逻辑
    };
    // 添加对话
    const handleAddDialog = (appId: number) => {
        console.log("添加对话" + appId);
        // 这里可以包含其他业务逻辑
    };



    return (
        <Flex vertical justify={"flex-start"} align={"center"} style={{width:'100%'}}>
            <span style = {{fontWeight:'700',fontSize:'xx-large',background:'linear-gradient(315deg, #7848f1, #4f0bff)',backgroundClip:'text',color:'transparent'}}>小应用，大创作</span>

            <div className={"tabButtonContainer"} style={{ marginTop: '10px', maxWidth:'80%', overflowX:'auto', whiteSpace:'nowrap'}} >
                {templateData.cats.map((cat) => (
                    <button
                        key={cat.id}
                        onClick={() => handleButtonClick(cat.id)}
                        style={{ margin: '5px', gap:'4px'}}
                        className={selectedButtonId === cat.id ? 'selected tabButton' : 'notSelected tabButton'}
                    >
                        <IconComponent iconName={cat.icon}/>
                        {cat.name}
                    </button>
                ))}
            </div>

            <Space.Compact style={{ width: '80%', marginTop:'10px', marginBottom: '10px'}}>
                <Input placeholder="输入关键字查询应用"
                       prefix={<SearchOutlined />}
                       allowClear
                       ref={inputRef}
                       onChange={handleSearchChange}
                       onPressEnter={handleSearchClickV2}
                       style={{width: '100%' }}
                       />
                <Button type="primary" className={"searchButton"}
                        disabled={searchButtonDisabled} // 使用 disabled 属性来控制按钮状态
                        onClick={handleSearchClickV2}>搜索</Button>
            </Space.Compact>

            <div className="grid-container">
                {appData.records.map(record => (
                    <Card key={record.id}  className={"appCard"} styles={{ body: { padding: '12px', paddingTop:'12px' } }} >
                        <Meta title={<span onClick={(e) => {
                            e.preventDefault();
                            handleUseApp(record.id);
                        }}>
                            {record.name}
                        </span>} avatar={<IconComponentTitle iconName={record.icon}/>} style={{marginLeft:"8px", fontSize:"24px"}}></Meta>
                        <div style={{ position: 'relative', width: '100%', display: 'flex', justifyContent: 'flex-start', paddingTop:'4px', flexWrap:"wrap"}}>
                            <Tooltip title="使用应用">
                                <Button onClick={() => {handleUseApp(record.id);}} style={{color:'#7848f1', backgroundColor:"#d9cff3", width:"20px"}} className={"opButton"} icon={<CaretRightOutlined />} />
                            </Tooltip>
                            <Tooltip title="收藏">
                                <Button onClick={() => {handleSubscribeApp(record.id);}} style={{color:'sandybrown', backgroundColor:"#f9e7cc", width:"20px"}} className={"opButton"} icon={<StarOutlined />} />
                            </Tooltip>
                            <button onClick={() => {handleButtonClick(record.category.id);}} className={"opButtonLong"}
                                    style={{background:"#c8e0f8", color:"#0573df"}} >
                                <IconComponent iconName={record.category.icon}/>{record.category.name}
                            </button>
                            <button onClick={() => {handleAddDialog(record.id);}} className={"opButtonLong"} >
                                <IconComponent iconName="fa-solid fa-comments"/>添至对话
                            </button>
                        </div>
                        <p className={"appDescription"}>{record.description}</p>

                    </Card>
                ))}
            </div>
        </Flex>
    );

}